'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 统计在线人数
 * @author agl
 */
var _ = require('lodash');
var moment = require('moment');
var pomelo = require('pomelo');
var async = require('async');
var channelUtil = require('../../util/channelUtil');
var analyze = require('../analyze');
var onlineUserCountService = require('../../services/onlineUserCountService.js');

var online_user_count_info = [];

/**
 * 统计在线用户数
 */
var _saveOnlineUserCount = function () {
    var sys_tm = +moment().startOf('minute').format('YYYYMMDDhhmm');
    onlineUserCountService.getOnlineInfo(function (err, online_info) {
        var curr_online_info = _.clone(online_info, true);
        var idx = Math.floor(sys_tm % 100 / 10);
        var i;
        if (online_user_count_info.length === 0) {
            for (i = 0; i < 6; i++) {
                online_user_count_info.push(curr_online_info);
            }
        } else {
            online_user_count_info[idx] = curr_online_info;
        }
        if (idx === 0) {
            var avg_user_count = {};
            var _totalAllChannel = function (user_count) {
                var keys = _.keys(user_count);
                _.forEach(keys, function (channel_id) {
                    avg_user_count[channel_id] = (avg_user_count[channel_id] || 0) + user_count[channel_id];
                });
            };
            for (i = 0; i < 6; i++) {
                _totalAllChannel(online_user_count_info[i]);
            }

            var sys_tm_h = Math.floor(sys_tm / 100);
            var avg_keys = _.keys(avg_user_count);
            _.forEach(avg_keys, function (channel_id) {
                avg_user_count[channel_id] = Math.ceil(avg_user_count[channel_id] / 6);
                if (avg_user_count[channel_id] > 0) {
                    analyze.recordOnlineUserCount(channel_id, sys_tm_h, avg_user_count[channel_id]);
                }
            });
        }
    });
};

module.exports = function () {
    if ((moment().minute() % 10) === 0) {
        // 每10分钟统计一次
        _saveOnlineUserCount();
    } else {
        // console.log('未到达统计时间');
    }
};
